package com.imast.android.bys.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONObject;

import android.util.Log;

import com.imast.android.bys.Config;

import static com.imast.android.bys.util.LogUtils.*;

public class ServerUtils {
	
	private static final String TAG = ServerUtils.class.getSimpleName();

	public static String sendRequest(String serviceOperation, JSONObject jsonParams, String requestMethod)
	throws IOException{
		
		HttpURLConnection httpConnection = null;
		OutputStream outputStream = null;
		BufferedReader bufferedReader = null;
		StringBuilder response = null;
		
		String jsonResult = "";
		
		try {
			
			URL url = new URL(Config.SERVICE_URL3 + serviceOperation);
			httpConnection = (HttpURLConnection) url.openConnection();
			httpConnection.setReadTimeout(60000);
			httpConnection.setConnectTimeout(30000);
			httpConnection.setRequestMethod(requestMethod);
			httpConnection.setDoInput(true);
			httpConnection.setDoOutput(true);
				
			httpConnection.setRequestProperty("Content-Type", "application/json");
			httpConnection.connect();
				
			outputStream = httpConnection.getOutputStream();
			outputStream.write(jsonParams.toString().getBytes());
			outputStream.flush();
			outputStream.close();
				
			bufferedReader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
			String line;
			response = new StringBuilder();
				
			while ((line = bufferedReader.readLine()) != null)
			{
				response.append(line);
			}
				
			Log.d(TAG, requestMethod + " response code: " + String.valueOf(httpConnection.getResponseCode()));
			Log.d(TAG, "JSON response: " + response.toString());
				
			jsonResult = response.toString();
			
		} catch (MalformedURLException e) {
			LOGE(TAG, e.getMessage());
			e.printStackTrace();
		} finally {
			httpConnection.disconnect();
			LOGD(TAG, "finally - disconnect");
		}
		
		return jsonResult;
		
	}
	
}
